package com.java.web.lucene;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.mail.Store;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class DbLucene {
	
	public static void bulidIndex(){
		Connection connect=null;
		PreparedStatement read=null;
		ResultSet result=null;
		String sql="select * from t_user";
		connect=DbUtils.getConn();
		
		try {
			File indexDir = new File("e:\\lucene\\\\db\\index");
			Directory dir = FSDirectory.open(indexDir);
			Analyzer luceneAnalyzer = new StandardAnalyzer(Version.LUCENE_36);
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_36,luceneAnalyzer);
			iwc.setOpenMode(OpenMode.CREATE);
			IndexWriter indexWriter = new IndexWriter(dir, iwc);
			
			read=connect.prepareStatement(sql);
			result=read.executeQuery();
			while(result.next()){
				Document doc=new Document();
				doc.add(new Field("id",result.getString("id"),Field.Store.YES,Field.Index.NO));
				doc.add(new Field("username",result.getString("username"),Field.Store.YES,Field.Index.ANALYZED));
				doc.add(new Field("truename",result.getString("truename"),Field.Store.YES,Field.Index.ANALYZED));
				indexWriter.addDocument(doc);
			}
			indexWriter.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			DbUtils.free(result, read, connect);
		}
	}
	
	/**
	 * 能查询各种结果，模糊查询
	 * @Method: parserQuery 
	 * @Description: TODO
	 * @param queryStr
	 * @return:void
	 */
	public static void parserQuery(String queryStr){
		 IndexSearcher searcher=getIndexSearcher();
         try{    
            Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);  
            //指定搜索的字段名称
            QueryParser queryParser = new QueryParser(Version.LUCENE_36,"username", analyzer);    
            Query query = queryParser.parse(queryStr);    
	        if (searcher != null) {    
	            TopDocs topDocs = searcher.search(query,10);    // 返回最多为10条记录
	            ScoreDoc scoreDocs[]=topDocs.scoreDocs;
	            //获得记录总数
			    int total=topDocs.totalHits;
	           
	            if (total> 0) {    
	                System.out.println("找到:" +total+ " 个结果!");    
	            } 
	            for (ScoreDoc scoreDoc : scoreDocs) {  
		            System.out.println("----------------分割线----------------------");  
		            Document hitDoc = searcher.doc(scoreDoc.doc);  
		            String truename=hitDoc.get("truename");
		            String username=hitDoc.get("username");;
		            float i = scoreDoc.score;  
		            String address = hitDoc.get("path");  
		            System.out.println("username:"+username+"\ntruename:"+truename+"\npath:" + address+"\nsocre:"+i);  
		        }
	            searcher.close(); 
	        }  
            
        } catch (Exception e) {    
        	throw new RuntimeException(e);
        } 
       
	}
	
	/**
	 * TermQuery查询
	 * @Method: termQuery 
	 * @Description: 只能指定字符串绝对匹配的结果
	 * @param queryStr
	 * @return:void
	 */
	public static void termQuery(String queryStr){  
	   IndexSearcher searcher=getIndexSearcher();
       Term term=new Term("username",queryStr);
       Query query=new TermQuery(term);
       try{ 
		   if (searcher != null) {    
		       TopDocs topDocs = searcher.search(query,10);    // 返回最多为10条
		       ScoreDoc scoreDocs[]=topDocs.scoreDocs;
		       int total=topDocs.totalHits;
		       if (total> 0) {    
		            System.out.println("找到:" +total+ " 个结果!");    
		       } 
		       for (ScoreDoc scoreDoc : scoreDocs) {  
		            System.out.println("----------------分割线----------------------");  
		            Document hitDoc = searcher.doc(scoreDoc.doc);  
		            String truename=hitDoc.get("truename");
		            String username=hitDoc.get("username");;
		            float i = scoreDoc.score;  
		            String address = hitDoc.get("path");  
		            System.out.println("username:"+username+"\ntruename:"+truename+"\npath:" + address+"\nsocre:"+i);  
		       }
		       searcher.close(); 
		   } 
		   
	   }catch (Exception e) {
		   throw new RuntimeException(e);
	   }
	}
	
	/**
	 * 获得IndexSearcher
	 * @Method: getIndexSearcher 
	 * @Description: TODO
	 * @return
	 * @return:IndexSearcher
	 */
	private static IndexSearcher getIndexSearcher(){
		String indexDir="e:\\lucene\\\\db\\index";
		IndexReader reader=null;
		try{
			reader = IndexReader.open(FSDirectory.open(new File(indexDir)));  
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
   		IndexSearcher searcher = new IndexSearcher(reader);    
		return searcher;
	}
	
	

}
